// 后台管理页面JavaScript模块
class AdminManager {
    constructor() {
        this.currentConfig = null;
        this.editingApp = null;
        this.filteredApps = null;
        
        this.initializeElements();
        this.setupEventListeners();
        this.loadConfig();
    }

    // 初始化DOM元素
    initializeElements() {
        this.elements = {
            // 主要容器
            appsTableBody: document.getElementById('appsTableBody'),
            appModal: document.getElementById('appModal'),
            toast: document.getElementById('toast'),
            toastIcon: document.getElementById('toastIcon'),
            toastMessage: document.getElementById('toastMessage'),
            
            // 表单元素
            appName: document.getElementById('appName'),
            appId: document.getElementById('appId'),
            appSecret: document.getElementById('appSecret'),
            gameName: document.getElementById('gameName'),
            appNameError: document.getElementById('appNameError'),
            appIdError: document.getElementById('appIdError'),
            gameNameError: document.getElementById('gameNameError'),
            modalTitle: document.getElementById('modalTitle'),
            
            // 按钮
            refreshBtn: document.getElementById('refreshBtn'),
            addAppBtn: document.getElementById('addAppBtn'),
            cancelModalBtn: document.getElementById('cancelModalBtn'),
            saveAppBtn: document.getElementById('saveAppBtn'),
            
            // 搜索和过滤
            searchInput: document.getElementById('searchInput'),
            filterSelect: document.getElementById('filterSelect'),
            
            // 批量操作元素
            batchActions: document.getElementById('batchActions'),
            selectedCount: document.getElementById('selectedCount'),
            selectAll: document.getElementById('selectAll'),
            batchDeleteBtn: document.getElementById('batchDeleteBtn'),
            batchCancelBtn: document.getElementById('batchCancelBtn')
        };
        
        // 批量选择状态
        this.selectedApps = new Set();
    }

    // 设置事件监听器
    setupEventListeners() {
        // 刷新按钮
        this.elements.refreshBtn.addEventListener('click', () => this.loadConfig());
        
        // 添加应用按钮
        this.elements.addAppBtn.addEventListener('click', () => this.openModal('添加应用配置'));
        
        // 模态框按钮
        this.elements.cancelModalBtn.addEventListener('click', () => this.closeModal());
        this.elements.saveAppBtn.addEventListener('click', () => this.saveAppConfig());
        
        // 批量操作事件
        this.elements.selectAll.addEventListener('change', (e) => this.toggleSelectAll(e.target.checked));
        this.elements.batchDeleteBtn.addEventListener('click', () => this.batchDeleteApps());
        this.elements.batchCancelBtn.addEventListener('click', () => this.cancelBatchSelection());
        
        // 搜索和过滤
        if (this.elements.searchInput) {
            this.elements.searchInput.addEventListener('input', () => this.filterApps());
        }
        if (this.elements.filterSelect) {
            this.elements.filterSelect.addEventListener('change', () => this.filterApps());
        }
        
        // 模态框外部点击关闭
        this.elements.appModal.addEventListener('click', (e) => {
            if (e.target === this.elements.appModal) {
                this.closeModal();
            }
        });
        
        // 键盘事件
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && !this.elements.appModal.classList.contains('hidden')) {
                this.closeModal();
            }
        });
    }

    // 加载配置
    async loadConfig() {
        this.showLoading(true);
        
        try {
            const response = await fetch('/getAppConfigs');
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const config = await response.json();
            this.currentConfig = config;
            this.filteredApps = null; // 重置过滤结果
            await this.updateAppsTable();
            this.showToast('配置加载成功', 'success');
        } catch (error) {
            console.error('加载配置失败:', error);
            this.showToast(`加载配置失败: ${error.message}`, 'error');
        } finally {
            this.showLoading(false);
        }
    }

    // 更新应用配置表格
    async updateAppsTable() {
        const apps = this.filteredApps || (this.currentConfig?.apps || {});
        const tableBody = this.elements.appsTableBody;
        
        tableBody.innerHTML = '';

        if (!apps || Object.keys(apps).length === 0) {
            const emptyRow = document.createElement('tr');
            emptyRow.innerHTML = `
                <td colspan="6" class="px-6 py-12 text-center text-gray-500">
                    <i class="fa fa-info-circle mr-2"></i> 暂无应用配置
                </td>
            `;
            tableBody.appendChild(emptyRow);
            return;
        }

        // 遍历所有应用配置
        for (const [appName, appConfig] of Object.entries(apps)) {
            const isSelected = this.selectedApps.has(appName);
            const row = document.createElement('tr');
            row.className = `hover:bg-gray-50 transition-colors ${isSelected ? 'bg-blue-50' : ''}`;
            
            // 异步检查文件夹是否存在
            const folderExists = await this.checkFolderExists(appName);
            
            row.innerHTML = `
                <td class="px-6 py-4 whitespace-nowrap">
                    <input type="checkbox" class="app-checkbox rounded border-gray-300 text-primary focus:ring-primary" 
                           data-app="${this.escapeHtml(appName)}" ${isSelected ? 'checked' : ''}>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${this.escapeHtml(appName)}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${this.escapeHtml(appConfig.AppId || '')}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${this.escapeHtml(appConfig.Secret || '')}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm">
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${folderExists ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}">
                        <i class="fa ${folderExists ? 'fa-check-circle' : 'fa-exclamation-triangle'} mr-1"></i>
                        ${folderExists ? '文件夹已创建' : '文件夹缺失'}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                    <button class="text-primary hover:text-primary/80 mr-3 edit-btn" data-app="${this.escapeHtml(appName)}">
                        <i class="fa fa-edit"></i> 编辑
                    </button>
                    <button class="text-danger hover:text-danger/80 delete-btn" data-app="${this.escapeHtml(appName)}">
                        <i class="fa fa-trash"></i> 删除
                    </button>
                </td>
            `;
            tableBody.appendChild(row);
        }

        // 添加编辑和删除按钮的事件监听器
        this.attachButtonListeners();
        this.attachCheckboxListeners();
        this.updateBatchActions();
    }

    // 附加按钮事件监听器
    attachButtonListeners() {
        document.querySelectorAll('.edit-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const appName = e.currentTarget.getAttribute('data-app');
                this.editAppConfig(appName);
            });
        });

        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const appName = e.currentTarget.getAttribute('data-app');
                this.deleteAppConfig(appName);
            });
        });
    }

    // 过滤应用
    async filterApps() {
        if (!this.currentConfig?.apps) return;
        
        const searchTerm = this.elements.searchInput?.value.toLowerCase() || '';
        const filterType = this.elements.filterSelect?.value || 'all';
        
        this.filteredApps = Object.entries(this.currentConfig.apps)
            .filter(([appName, appConfig]) => {
                const matchesSearch = appName.toLowerCase().includes(searchTerm) ||
                                    (appConfig.AppId || '').toLowerCase().includes(searchTerm);
                
                const matchesFilter = filterType === 'all' || 
                                    (filterType === 'hasId' && appConfig.AppId) ||
                                    (filterType === 'noId' && !appConfig.AppId);
                
                return matchesSearch && matchesFilter;
            })
            .reduce((acc, [appName, appConfig]) => {
                acc[appName] = appConfig;
                return acc;
            }, {});
        
        await this.updateAppsTable();
    }

    // 打开模态框
    openModal(title) {
        this.elements.modalTitle.textContent = title;
        this.elements.appName.value = '';
        this.elements.appId.value = '';
        this.elements.appSecret.value = '';
        this.elements.gameName.value = '';
        this.elements.appName.disabled = false;
        this.elements.appNameError.classList.add('hidden');
        this.elements.gameNameError.classList.add('hidden');
        this.elements.appModal.classList.remove('hidden');
        this.editingApp = null;
        
        // 聚焦到第一个输入框
        setTimeout(() => this.elements.appName.focus(), 100);
    }

    // 关闭模态框
    closeModal() {
        this.elements.appModal.classList.add('hidden');
        this.editingApp = null;
    }

    // 编辑应用配置
    editAppConfig(appName) {
        const appConfig = this.currentConfig?.apps?.[appName];
        if (!appConfig) return;

        this.elements.modalTitle.textContent = '编辑应用配置';
        this.elements.appName.value = appName;
        this.elements.appName.disabled = true;
        this.elements.appId.value = appConfig.AppId || '';
        this.elements.appSecret.value = appConfig.Secret || '';
        this.elements.gameName.value = appConfig.gameName || '';
        this.elements.appModal.classList.remove('hidden');
        this.editingApp = appName;
        
        // 聚焦到AppId输入框
        setTimeout(() => this.elements.appId.focus(), 100);
    }

    // 保存应用配置
    async saveAppConfig() {
        const appName = this.elements.appName.value.trim();
        const appId = this.elements.appId.value.trim();
        const appSecret = this.elements.appSecret.value.trim();
        const gameName = this.elements.gameName.value.trim();

        // 验证输入
        if (!this.validateInput(appName, appId, appSecret, gameName)) {
            return;
        }

        this.showLoading(true);
        
        try {
            const response = await fetch('/updateAppConfig', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 
                    appName, 
                    appConfig: { AppId: appId, Secret: appSecret, gameName: gameName }
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const result = await response.json();
            
            if (result.success) {
                // 更新本地配置
                if (!this.currentConfig.apps) {
                    this.currentConfig.apps = {};
                }
                this.currentConfig.apps[appName] = { AppId: appId, Secret: appSecret, gameName: gameName };
                this.filteredApps = null; // 重置过滤结果
            await this.updateAppsTable();
            this.closeModal();
                
                // 检查是否是新增应用，显示文件夹创建信息
                const isNewApp = !this.editingApp;
                if (isNewApp) {
                    this.showToast(`应用配置保存成功，已自动创建 ${appName} 文件夹和配置文件`, 'success');
                } else {
                    this.showToast('应用配置保存成功', 'success');
                }
            } else {
                throw new Error(result.message || '未知错误');
            }
        } catch (error) {
            console.error('保存应用配置失败:', error);
            this.showToast(`保存应用配置失败: ${error.message}`, 'error');
        } finally {
            this.showLoading(false);
        }
    }

    // 验证输入
    validateInput(appName, appId, appSecret, gameName) {
        // 清除之前的错误状态
        this.elements.appNameError.classList.add('hidden');
        this.elements.appIdError.classList.add('hidden');
        this.elements.gameNameError.classList.add('hidden');
        
        let isValid = true;

        // 验证应用名称
        if (!appName) {
            this.elements.appNameError.textContent = '应用名称不能为空';
            this.elements.appNameError.classList.remove('hidden');
            this.elements.appName.focus();
            isValid = false;
        }

        // 检查应用名称是否已存在（新增时）
        if (!this.editingApp && this.currentConfig.apps && this.currentConfig.apps[appName]) {
            this.elements.appNameError.textContent = '应用名称已存在';
            this.elements.appNameError.classList.remove('hidden');
            this.elements.appName.focus();
            isValid = false;
        }

        // 验证AppId格式（可选）
        if (appId && !/^[a-zA-Z0-9_-]+$/.test(appId)) {
            this.elements.appIdError.textContent = 'AppId格式不正确，只能包含字母、数字、下划线和连字符';
            this.elements.appIdError.classList.remove('hidden');
            this.elements.appId.focus();
            isValid = false;
        }

        // 验证游戏名长度
        if (gameName.length > 100) {
            this.elements.gameNameError.textContent = '游戏名不能超过100个字符';
            this.elements.gameNameError.classList.remove('hidden');
            this.elements.gameName.focus();
            isValid = false;
        }

        // 实时验证应用名称长度
        if (appName.length > 50) {
            this.elements.appNameError.textContent = '应用名称不能超过50个字符';
            this.elements.appNameError.classList.remove('hidden');
            this.elements.appName.focus();
            isValid = false;
        }

        return isValid;
    }

    // 删除应用配置
    async deleteAppConfig(appName) {
        // 使用更友好的确认对话框
        const confirmed = await this.showConfirmDialog(
            '确认删除',
            `确定要删除应用 "${appName}" 的配置吗？此操作不可撤销。`,
            '删除',
            '取消'
        );
        
        if (!confirmed) {
            return;
        }

        this.showLoading(true);
        
        try {
            const response = await fetch('/deleteAppConfig', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ appName })
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const result = await response.json();
            
            if (result.success) {
                // 更新本地配置
                if (this.currentConfig.apps && this.currentConfig.apps[appName]) {
                    delete this.currentConfig.apps[appName];
                }
                this.filteredApps = null; // 重置过滤结果
                await this.updateAppsTable();
                this.showToast(`应用配置删除成功，已删除 ${appName} 文件夹`, 'success');
            } else {
                throw new Error(result.message || '未知错误');
            }
        } catch (error) {
            console.error('删除应用配置失败:', error);
            this.showToast(`删除应用配置失败: ${error.message}`, 'error');
        } finally {
            this.showLoading(false);
        }
    }

    // 显示加载状态
    showLoading(show) {
        document.body.style.cursor = show ? 'wait' : 'default';
        
        // 禁用所有按钮
        const buttons = document.querySelectorAll('button');
        buttons.forEach(btn => {
            btn.disabled = show;
        });
        
        // 添加加载指示器到表格
        const tableBody = this.elements.appsTableBody;
        if (show) {
            tableBody.innerHTML = `
                <tr>
                    <td colspan="4" class="px-6 py-12 text-center text-gray-500">
                        <i class="fa fa-spinner fa-spin mr-2"></i> 加载中...
                    </td>
                </tr>
            `;
        }
    }

    // 显示提示消息
    showToast(message, type = 'success') {
        this.elements.toastMessage.textContent = message;
        
        // 设置样式
        if (type === 'success') {
            this.elements.toast.className = 'fixed bottom-4 right-4 px-6 py-3 bg-green-500 text-white rounded-md shadow-lg transform translate-y-0 opacity-100 transition-all duration-300 flex items-center z-50';
            this.elements.toastIcon.className = 'fa fa-check-circle mr-2';
        } else {
            this.elements.toast.className = 'fixed bottom-4 right-4 px-6 py-3 bg-red-500 text-white rounded-md shadow-lg transform translate-y-0 opacity-100 transition-all duration-300 flex items-center z-50';
            this.elements.toastIcon.className = 'fa fa-exclamation-circle mr-2';
        }
        
        // 显示3秒后自动隐藏
        setTimeout(() => {
            this.elements.toast.style.transform = 'translateY(16px)';
            this.elements.toast.style.opacity = '0';
        }, 3000);
    }

    // 显示确认对话框
    showConfirmDialog(title, message, confirmText = '确认', cancelText = '取消') {
        return new Promise((resolve) => {
            // 创建对话框元素
            const dialog = document.createElement('div');
            dialog.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
            dialog.innerHTML = `
                <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
                    <div class="px-6 py-4 border-b">
                        <h3 class="text-lg font-semibold text-gray-900">${title}</h3>
                    </div>
                    <div class="px-6 py-4">
                        <p class="text-gray-700">${message}</p>
                    </div>
                    <div class="px-6 py-4 border-t flex justify-end space-x-3">
                        <button class="px-4 py-2 text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50" id="confirmCancel">${cancelText}</button>
                        <button class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700" id="confirmOk">${confirmText}</button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(dialog);
            
            // 添加事件监听器
            const confirmOk = dialog.querySelector('#confirmOk');
            const confirmCancel = dialog.querySelector('#confirmCancel');
            
            const cleanup = () => {
                document.body.removeChild(dialog);
            };
            
            confirmOk.onclick = () => {
                cleanup();
                resolve(true);
            };
            
            confirmCancel.onclick = () => {
                cleanup();
                resolve(false);
            };
            
            // ESC键关闭
            const escHandler = (e) => {
                if (e.key === 'Escape') {
                    cleanup();
                    resolve(false);
                }
            };
            
            document.addEventListener('keydown', escHandler);
            
            // 点击背景关闭
            dialog.onclick = (e) => {
                if (e.target === dialog) {
                    cleanup();
                    resolve(false);
                }
            };
            
            // 焦点管理
            setTimeout(() => confirmCancel.focus(), 100);
        });
    }

    // 批量操作相关方法
    
    // 附加复选框事件监听器
    attachCheckboxListeners() {
        const checkboxes = document.querySelectorAll('.app-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.addEventListener('change', (e) => {
                const appName = e.target.dataset.app;
                if (e.target.checked) {
                    this.selectedApps.add(appName);
                } else {
                    this.selectedApps.delete(appName);
                }
                this.updateBatchActions();
                this.updateSelectAllState();
            });
        });
    }
    
    // 切换全选状态
    async toggleSelectAll(checked) {
        const apps = this.filteredApps || Object.entries(this.currentConfig?.apps || {});
        
        if (checked) {
            apps.forEach(([appName]) => {
                this.selectedApps.add(appName);
            });
        } else {
            this.selectedApps.clear();
        }
        
        await this.updateAppsTable();
    }
    
    // 更新全选复选框状态
    updateSelectAllState() {
        const apps = this.filteredApps || Object.entries(this.currentConfig?.apps || {});
        const allSelected = apps.length > 0 && apps.every(([appName]) => this.selectedApps.has(appName));
        this.elements.selectAll.checked = allSelected;
        this.elements.selectAll.indeterminate = !allSelected && this.selectedApps.size > 0;
    }
    
    // 更新批量操作界面
    updateBatchActions() {
        const count = this.selectedApps.size;
        
        if (count > 0) {
            this.elements.batchActions.classList.remove('hidden');
            this.elements.selectedCount.textContent = `已选择 ${count} 项`;
        } else {
            this.elements.batchActions.classList.add('hidden');
        }
    }
    
    // 取消批量选择
    async cancelBatchSelection() {
        this.selectedApps.clear();
        await this.updateAppsTable();
    }
    
    // 批量删除应用
    async batchDeleteApps() {
        const appNames = Array.from(this.selectedApps);
        if (appNames.length === 0) return;
        
        const confirmed = await this.showConfirmDialog(
            '确认批量删除',
            `确定要删除选中的 ${appNames.length} 个应用配置吗？此操作不可撤销。`,
            '批量删除',
            '取消'
        );
        
        if (!confirmed) {
            return;
        }
        
        this.showLoading(true);
        
        try {
            const response = await fetch('/batchDeleteAppConfigs', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ appNames })
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const result = await response.json();
            
            if (result.success) {
                // 更新本地配置
                appNames.forEach(appName => {
                    if (this.currentConfig.apps && this.currentConfig.apps[appName]) {
                        delete this.currentConfig.apps[appName];
                    }
                });
                this.filteredApps = null; // 重置过滤结果
                await this.updateAppsTable();
                this.cancelBatchSelection();
                this.showToast(`成功删除 ${appNames.length} 个应用配置，已删除对应文件夹`, 'success');
            } else {
                throw new Error(result.message || '未知错误');
            }
        } catch (error) {
            console.error('批量删除应用配置失败:', error);
            this.showToast(`批量删除失败: ${error.message}`, 'error');
        } finally {
            this.showLoading(false);
        }
    }

    // 转义HTML特殊字符
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    // 检查应用文件夹是否存在
    async checkFolderExists(appName) {
        try {
            const response = await fetch('/checkAppFolder', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ appName })
            });
            
            if (response.ok) {
                const result = await response.json();
                return result.folderExists && result.configExists;
            }
        } catch (error) {
            console.error('检查文件夹状态失败:', error);
        }
        
        // 如果API调用失败，返回false表示文件夹状态未知
        return false;
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    window.adminManager = new AdminManager();
});